package cn.guozeyiblog.client;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.guozeyiblog.client.UpdateActivity.AsyGetNewVersion;
import cn.guozeyiblog.netutils.HttpUtil;
import cn.guozeyiblog.netutils.NetWorkStatus;

public class WeatherActivity extends Activity implements OnClickListener{
	private ImageView backButton;
	private ImageView shareButton;
	private TextView weather_today_date;
	private String Sweather_today_date="";
	private TextView weather_today_temperature;
	private String Sweather_today_temperature="";
	private TextView weather_today_weekday;
	private String Sweather_today_weekday="";
	private TextView weather_information;
	private String sweather_information="";
	private TextView weather_after1;
	private String Sweather_after1="";
	private TextView weather_after2;
	private String Sweather_after2="";
	private TextView weather_after3;
	private String Sweather_after3="";
	private TextView weather_city;
	private String Sweather_city="";
	private TextView weather_updatetime;
	private String Sweather_updatetime="";
	private ImageView weather_refush;
	private Animation updateAnimation;
	private SharedPreferences preferences;
	private TextView weather_title_city;
	private final static int NET_ERROR=-1;
	private final static int STATUS_ERROR=-2;
	private final static int SUSSESS=0;

	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case NET_ERROR:
			case STATUS_ERROR:
				Toast.makeText(getApplicationContext(), "网络错误,稍后再试", 0).show();
				break;
            case SUSSESS:
            	weather_today_date.setText(Sweather_today_date);
            	weather_after1.setText(Sweather_after1);
            	weather_after2.setText(Sweather_after2);
            	weather_after3.setText(Sweather_after3);
            	weather_city.setText(Sweather_city);
            	weather_title_city.setText(Sweather_city);
            	weather_information.setText(sweather_information);
            	weather_today_temperature.setText(Sweather_today_temperature);
            	//weather_today_weekday.setText(Sweather_today_weekday);
            	weather_updatetime.setText(Sweather_updatetime);
            	weather_refush.clearAnimation();
            	new Thread(){
            		public void run() {
            			Editor editor = preferences.edit();
            			editor.putString("Sweather_today_date", Sweather_today_date);
            			editor.putString("Sweather_after1", Sweather_after1);
            			editor.putString("Sweather_after2", Sweather_after2);
            			editor.putString("Sweather_after3", Sweather_after3);
            			editor.putString("Sweather_city", Sweather_city);
            			editor.putString("sweather_information", sweather_information);
            			editor.putString("Sweather_today_temperature", Sweather_today_temperature);
            			editor.putString("Sweather_today_weekday", Sweather_today_weekday);
            			editor.putString("Sweather_updatetime", Sweather_updatetime);
            			editor.commit();
            		};
            	}.start();
            	
            	break;
			default:
				break;
			}
		};
	};
	
	
	/**
	 * 通过Json解析数据
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.weather_activity);
		initView();
		updateAnimation = AnimationUtils.loadAnimation(this, R.anim.update);
		preferences = getSharedPreferences("cn.guozeyiblog.client_preferences", Context.MODE_PRIVATE);
		backButton.setClickable(true);
		shareButton.setClickable(true);
		backButton.setOnClickListener(this);
		shareButton.setOnClickListener(this);
		weather_city.setOnClickListener(this);
		weather_title_city.setOnClickListener(this);
		Sweather_city = preferences.getString("Sweather_city", "北京");
		weather_title_city.setText( preferences.getString("Sweather_city", "北京"));
		if(NetWorkStatus.isNetworkAvailable(getApplicationContext())){
			new Thread(){public void run() {
				Sweather_after1 = preferences.getString("Sweather_after1", "NULL");
				Sweather_after2 = preferences.getString("Sweather_after2", "NULL");
				Sweather_after3 = preferences.getString("Sweather_after3", "NULL");
				Sweather_today_date = preferences.getString("Sweather_today_date", "NULL");
				Sweather_updatetime = preferences.getString("Sweather_updatetime", "NULL");
				Sweather_today_weekday = preferences.getString("Sweather_today_weekday", "NULL");
				Sweather_today_temperature = preferences.getString("Sweather_today_temperature", "NULL");
				sweather_information = preferences.getString("sweather_information", "NULL");
				handler.sendEmptyMessage(SUSSESS);
			};}.start();
		}else {
			Toast.makeText(getApplicationContext(), "你的网络不可用哦", 0).show();
		}
		
		weather_refush.setClickable(true);
		weather_refush.setOnClickListener(this);
		weather_refush.startAnimation(updateAnimation);
		if(NetWorkStatus.isNetworkAvailable(getApplicationContext())){
			new AsyGetWeatherInfo().execute("http://api.map.baidu.com/telematics/v3/weather?location="+Sweather_city+"&output=json&ak=4h4DbcjKVquzDWLjYfzMCexc");
		}else {
			Toast.makeText(getApplicationContext(), "你的网络不可用哦", 0).show();
		}
		
	}

	private void initView(){
          backButton = (ImageView) findViewById(R.id.weather_back);
          shareButton = (ImageView) findViewById(R.id.weather_share);
          weather_after1 = (TextView) findViewById(R.id.weather_after1);
          weather_after2 = (TextView) findViewById(R.id.weather_after2);
          weather_after3 = (TextView) findViewById(R.id.weather_after3);
          weather_information = (TextView) findViewById(R.id.weather_information);
          weather_refush = (ImageView) findViewById(R.id.weather_refush);
          weather_today_date = (TextView) findViewById(R.id.weather_today_date);
          weather_today_temperature = (TextView) findViewById(R.id.weather_today_temperature);
          weather_today_weekday = (TextView) findViewById(R.id.weather_today_weekday);
          weather_city = (TextView) findViewById(R.id.weather_city);
          weather_updatetime = (TextView) findViewById(R.id.weather_update_time);
          weather_title_city = (TextView) findViewById(R.id.weather_title_city);
	}
	

	/**
	 * 选择城市之后重新刷新
	 */
	@SuppressLint("NewApi")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (data==null) {
			return;
		}
		if(requestCode==0&&resultCode==0){
			//Sweather_city = data.getExtras().getString("city", "北京");
			Sweather_city = data.getStringExtra("city");
			
			preferences.edit().putString("Sweather_city", Sweather_city);
			weather_refush.startAnimation(updateAnimation);
			if(NetWorkStatus.isNetworkAvailable(getApplicationContext())){
				new AsyGetWeatherInfo().execute("http://api.map.baidu.com/telematics/v3/weather?location="+Sweather_city+"&output=json&ak=4h4DbcjKVquzDWLjYfzMCexc");
			}else {
				Toast.makeText(getApplicationContext(), "你的网络不可用哦", 0).show();
			}
		}
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.weather_share:
			//Toast.makeText(getApplicationContext(), "分享功能", 0).show();
			  Intent intent=new Intent(Intent.ACTION_SEND);      
		      intent.setType("text/plain");
		      intent.putExtra(Intent.EXTRA_SUBJECT,"天气分享");
		      intent.putExtra(Intent.EXTRA_TEXT, "今天"+Sweather_city+"的天气是:"+sweather_information+",温度是:"+Sweather_today_temperature);
		      startActivity(Intent.createChooser(intent, "天气"));
			
			break;
		case R.id.weather_back:
			this.finish();
			break;
			
		case R.id.weather_refush:
			//旋转动画
			weather_refush.startAnimation(updateAnimation);
			if(NetWorkStatus.isNetworkAvailable(getApplicationContext())){
				new AsyGetWeatherInfo().execute("http://api.map.baidu.com/telematics/v3/weather?location="+Sweather_city+"&output=json&ak=4h4DbcjKVquzDWLjYfzMCexc");
			}else {
				Toast.makeText(getApplicationContext(), "你的网络不可用哦", 0).show();
			}
			break;
		case R.id.weather_title_city:
		case R.id.weather_city:
			Log.v("AAA", "CITY");
			Intent intent2 = new Intent(WeatherActivity.this, CityListActivity.class);
			startActivityForResult(intent2, 0);
			break;
		default:
			break;
		}
	}
	
	
	//获取网络数据:
	public class AsyGetWeatherInfo extends AsyncTask<String, Void, Void>{

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			String result = HttpUtil.httpGet(params[0]);
			System.out.println(result);
			try {
				JSONObject ob = new JSONObject(result);
				if (ob.getInt("error")==0) {
					//Sweather_today_date = ob.getString("date");
					 JSONArray array = ob.getJSONArray("results").getJSONObject(0).getJSONArray("weather_data");
					 Sweather_city = ob.getJSONArray("results").getJSONObject(0).getString("currentCity");
					for (int i = 0; i < array.length(); i++) {
						JSONObject ob2=array.getJSONObject(i);
						switch (i) {
						case 0:
							System.out.println("----------------------------0");
							Sweather_today_date = ob2.getString("date");
							sweather_information = ob2.getString("weather")+"--"+ob2.getString("wind");
							Sweather_today_temperature = ob2.getString("temperature");
							break;
						case 1:
							System.out.println("----------------------------1");
							Sweather_after1 = ob2.getString("date")+"--"+ob2.getString("weather")+"--"+ob2.getString("wind")+"--"+ob2.getString("temperature");
							break;
						case 2:
							System.out.println("----------------------------2");
							Sweather_after2 = ob2.getString("date")+"--"+ob2.getString("weather")+"--"+ob2.getString("wind")+"--"+ob2.getString("temperature");;
							break;
						case 3:
							System.out.println("----------------------------3");
							Sweather_after3 = ob2.getString("date")+"--"+ob2.getString("weather")+"--"+ob2.getString("wind")+"--"+ob2.getString("temperature");;
							break;

						default:
							break;
						}
					}
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd:hh:mm:ss");
	            	Sweather_updatetime = format.format(new Date());
				handler.sendEmptyMessage(SUSSESS);
				}else {
					
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
			return null;
		}
		
	}
}
